/**
 *
 */
package name.yzhu.index.stem;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.chenlb.mmseg4j.ComplexSeg;
import com.chenlb.mmseg4j.Dictionary;
import com.chenlb.mmseg4j.MMSeg;
import com.chenlb.mmseg4j.Seg;
import com.chenlb.mmseg4j.Word;

import name.yzhu.common.conf.AbstractConfig;
import name.yzhu.common.yaml.YamlItem;

/**
 * @author yhzhu
 *
 */
public class MMSegStem extends AbstractStem {
	static private final Log LOG = LogFactory.getLog(MMSegStem.class);
	private Dictionary dic = null;

	public MMSegStem() {
	}

	@Override
	public void open() throws IOException {
		if (null == dictPath)
		    dic = Dictionary.getInstance();
		else
			dic = Dictionary.getInstance(dictPath);
	}

	@Override
	public void close() throws IOException {
	}
	/* (non-Javadoc)
	 * @see name.yzhu.index.stem.IStem#stem(java.lang.String)
	 */
	@Override
	public String stem(String txt) throws IOException {
		Reader input = null;
        try {
			Seg seg = new ComplexSeg(dic);
			input = new StringReader(txt);
			MMSeg mmSeg = new MMSeg(input, seg);
			StringBuilder sb = new StringBuilder();
			Word word = null;
			boolean first = true;
			while((word=mmSeg.next())!=null) {
				if(!first) {
					sb.append(DEFAULT_WORD_SPLIT);
				}
				String w = word.getString();
				sb.append(w);
				first = false;

			}
			return sb.toString();
        }
        finally {
           if (null != input){
        	   input.close();
        	   input = null;
           }
        }
	}

	/* (non-Javadoc)
	 * @see name.yzhu.index.stem.IStem#stem(name.yzhu.common.yaml.YamlItem)
	 */
	@Override
	public YamlItem stem(YamlItem yaml, AbstractConfig stemCfg) throws IOException {
		for(Entry<String, Object> e : yaml.entrySet()){
			if (e.getValue() instanceof String && stemCfg.contain(e.getKey())){
				yaml.put(e.getKey(), stem(String.valueOf(e.getValue())));
			}
		}
		return yaml;
	}

	@Override
	public boolean checkAndReloadDict() throws IOException {
		try {
			if (!dic.wordsFileIsChange())
				return false;
			dic.reload();
			return true;
		} catch (Exception e) {
			LOG.error("checkReloadDict error", e);
			throw new IOException(e);
		}
	}

	public List<String> stemToList(String txt) throws IOException {
		Reader input = null;
        try {
			Seg seg = new ComplexSeg(dic);
			input = new StringReader(txt);
			MMSeg mmSeg = new MMSeg(input, seg);
			List<String> sb = new ArrayList<String>();
			Word word = null;
			while((word=mmSeg.next())!=null) {
				sb.add(word.getString());
			}
			return sb;
        }
        finally {
           if (null != input){
        	   input.close();
        	   input = null;
           }
        }
	}
}
